package com.frost.blog.util;

import io.jsonwebtoken.*;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;

import java.security.Key;
import java.util.Date;
import java.util.Map;

import static com.frost.blog.constants.Constant.USER_CLAIM_ID;

@Slf4j
public class JWTUtils {

    private final static long EXPIRATION_DATE = 60 * 60 * 1000;

    private final static String secretString = "B6X7jGKKaUqSAPVUF8OxFvVsygtX884/5XMz2oN3Uko=";
    private final static Key key = Keys.hmacShaKeyFor(Decoders.BASE64.decode(secretString));

    // 生成令牌
    public static String getToken(Map<String, Object> claim) {
        return Jwts.builder()
                .setClaims(claim) // 设置信息
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_DATE)) // 设置过期时间
                .signWith(key) // 设置签名
                .compact();
    }

    // 生成key
//    public void getKey() {
//        SecretKey secretKey =  Keys.secretKeyFor(SignatureAlgorithm.HS256);
//        String encode = Encoders.BASE64.encode(secretKey.getEncoded()); // 获取签名(key)
//        System.out.println(encode);
//    }

    public static Claims parseToken(String token) {
        JwtParser build = Jwts.parserBuilder().setSigningKey(key).build();
        Claims body = null;
        try {
            log.info(token);
            body = build.parseClaimsJws(token).getBody();// 解析token
        } catch (ExpiredJwtException e) {
            log.error("token过期, 校验失败, token: " + token);
            return null;
        } catch (Exception e) {
            log.error("token校验失败, token: " + token);
            return null;
        }

        return body;
    }

    // 校验令牌
    public static boolean checkToken(String token) {
        Claims body = parseToken(token);
        return body != null;
    }

    // 从token中获取userId
    public static Integer getUserIdFromToken(String token) {
        Claims body = parseToken(token);
        if (body != null) {
            return (Integer) body.get(USER_CLAIM_ID);
        }
        return null;
    }
}
